package ca.eloas.gpsclock.ui;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import ca.eloas.gpsclock.Intents;
import ca.eloas.gpsclock.R;
import ca.eloas.gpsclock.db.AlarmDatabase;
import ca.eloas.gpsclock.db.TimeAlarmInfo;

import java.util.List;

/**
 * User: jpbelang
 * Date: Sep 28, 2010
 * Time: 8:42:18 AM
 */
public class AlarmActivity extends ListActivity implements TimePickerDialog.OnTimeSetListener {


    private AlarmDatabase database;
    private TimeAlarmArrayAdapter alarmArrayAdapter;

    private static final int TIME_PICKER_DIALOG = 1;
    
    private TimeAlarmInfo dialogAlarmInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.alarm);
        ListView listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        TextView empty = (TextView) findViewById(R.id.empty);
        listView.setEmptyView(empty);

        database = new AlarmDatabase(this);
    }


    public void onStart() {

        super.onStart();

        loadAlarmsInUI();
    }

    private void notifyAlarmChange(long id) {

        Intent intent = new Intent(Intents.CHANGED_ALARM);
        intent.putExtra("id", id);
        sendBroadcast(intent);
    }

    private void notifyAlarmDeleted(long id) {

        Intent intent = new Intent(Intents.DELETED_ALARM);
        intent.putExtra("id", id);
        sendBroadcast(intent);
    }


    private void loadAlarmsInUI() {
        final List<TimeAlarmInfo> alarmInfos = database.getAllAlarms();
        alarmArrayAdapter = new TimeAlarmArrayAdapter(alarmInfos);
        setListAdapter(alarmArrayAdapter);
        registerForContextMenu(getListView());

    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        dialogAlarmInfo.setHours(hourOfDay);
        dialogAlarmInfo.setMinutes(minute);
        database.saveAlarm(dialogAlarmInfo);
        notifyAlarmChange(dialogAlarmInfo.getId());

        dialogAlarmInfo = null;

        ArrayAdapter<TimeAlarmInfo> a = (ArrayAdapter<TimeAlarmInfo>) getListView().getAdapter();
        a.notifyDataSetChanged();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        
        switch(id) {
        
            case TIME_PICKER_DIALOG:
                
                TimePickerDialog tp = new TimePickerDialog(this, AlarmActivity.this, dialogAlarmInfo.getHours(), dialogAlarmInfo.getMinutes(), true);
                return tp;
            default:
                
                return null;
        }
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch(id) {

            case TIME_PICKER_DIALOG:

                TimePickerDialog tp = (TimePickerDialog) dialog;
                tp.updateTime(dialogAlarmInfo.getHours(), dialogAlarmInfo.getMinutes());
                return;
            default:

                return;
        }
    }

    @Override
    protected void onStop() {

        super.onStop();
        unregisterForContextMenu(getListView());
        setListAdapter(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        database.close();
        database = null;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.alarm_context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        switch (item.getItemId()) {
            case R.id.edit_time_alarm:
                Log.d("editing", "we bees editing");
                return true;
            case R.id.delete_time_alarm:
                TimeAlarmInfo alarmInfo = alarmArrayAdapter.getItem(info.position);
                alarmArrayAdapter.remove(alarmInfo);
                database.deleteAlarm(alarmInfo);
                notifyAlarmDeleted(alarmInfo.getId());
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }


    private class TimeAlarmArrayAdapter extends ArrayAdapter<TimeAlarmInfo>  {

        public TimeAlarmArrayAdapter(List<TimeAlarmInfo> alarmInfos) {
            super(AlarmActivity.this, R.layout.alarm_list_item, alarmInfos);
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {

            View rowView = convertView;
            if ( rowView == null ) {

                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rowView = inflater.inflate(R.layout.alarm_list_item, parent, false);
            }

            TextView t = (TextView) rowView.findViewById(R.id.ListAlarmTime);
            final TimeAlarmInfo alarmInfo = getItem(position);
            t.setText(alarmInfo.asString());
            rowView.setLongClickable(true);
            rowView.setClickable(true);

            final CheckBox cb = (CheckBox) rowView.findViewById(R.id.ListActive);
            cb.setOnCheckedChangeListener(null);
            cb.setChecked(alarmInfo.getActive());

            rowView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    dialogAlarmInfo = alarmInfo;
                    showDialog(TIME_PICKER_DIALOG);
                }
            });

            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    alarmInfo.setActive(isChecked);
                    database.saveAlarm(alarmInfo);
                    notifyAlarmChange(alarmInfo.getId());
                }
            });
            return rowView;
        }
    }
}
